package studio.raptor.ddal.dashboard.log.common;

import org.dom4j.Document;
import org.dom4j.Element;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 类名称 CommonMethodUtil <br>
 * 常用的方法工具类
 */
public class CommonMethodUtil {

	private final static byte[] hex = "0123456789ABCDEF".getBytes();

	/**
	 * 线程休眠函数
	 * @param time
	 */
	public static void waitSleep(long time){
		try {
			Thread.sleep(time);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
	}

	/**
	 * 将异常信息转成字符串输出
	 * Get the stack trace of the exception.
	 * @param e The exception instance.
	 * @return The full stack trace of the exception.
	 */
	public static String getExceptionTrace(Throwable e) {
		if (e != null) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			e.printStackTrace(pw);
			return sw.toString();
		}
		return "No Exception";
	}

	/**
	 * 从属性文件获取固定值
	 * @param proCode
	 * @return
	 */
	public static String getValueByProCode(String proCode) {
		Properties p = new Properties();
		try {
			p.load(CommonMethodUtil.class.getResourceAsStream("/system.properties"));
			return (String) p.get(proCode);
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	/**
	 * 从属性文件获取固定值
	 * @param proCode
	 * @return
	 */
	public static String getValueByProCode(String proCode,String defaultValue) {
		Properties p = new Properties();
		try {
			String returnValue="";
			p.load(CommonMethodUtil.class.getResourceAsStream("/system.properties"));
			if(p.get(proCode)==null||p.get(proCode).equals(""))
				returnValue = defaultValue;
			else
				returnValue = (String) p.get(proCode);
			return returnValue;
		} catch (IOException e) {
			e.printStackTrace();
			return null;
		}
	}

	public static String getNotNullString(String str){
		if(str!=null){
			return str;
		}else{
			return "";
		}
	}

	public static String getNotNullString(Long para){
		if(para!=null){
			return para.toString();
		}else{
			return "";
		}
	}

	//将paramMap根据key获取的值转成String并返回
	public static String getMapValueToString (Map paramMap,String key){
		String value ="";
		if (paramMap==null) return value;
		if(paramMap.get(key)!=null){
			if(paramMap.get(key) instanceof String){
				value =(String)paramMap.get(key);
				return value;
			}
			if(paramMap.get(key) instanceof java.math.BigDecimal){
				value =((java.math.BigDecimal)paramMap.get(key)).toString();
				return value;
			}
			if(paramMap.get(key) instanceof Boolean){
				value =((Boolean)paramMap.get(key)).toString();
				return value;
			}
		}else{
			value = "";
		}
		return value;
	}

	//将paramList根据number获取的值转成String并返回
	public static String getListValueToString (List paramList,int number){
		String value ="";
		if(paramList.get(number)!=null){
			if(paramList.get(number) instanceof String){
				value =(String)paramList.get(number);
				return value;
			}
			if(paramList.get(number) instanceof java.math.BigDecimal){
				value =((java.math.BigDecimal)paramList.get(number)).toString();
				return value;
			}
			if(paramList.get(number) instanceof Boolean){
				value =((Boolean)paramList.get(number)).toString();
				return value;
			}
		}else{
			value = "";
		}
		return value;
	}

	public static Map getMapValueToMap (Map paramMap,String key){
		Map map =null;
		if(paramMap.get(key)!=null){
			map = (Map)paramMap.get(key);
		}else{
			map=new HashMap();
		}
		return map;
	}

	/**
	 * 获取document文档中的文本内容
	 * @param document  文档
	 * @param position  路径
	 * @return
	 */
	public static String getTextByPosition(Document document, String position) {
		List list = document.selectNodes(position);
		if (list != null && list.size() != 0) {
			return ((Element) list.get(0)).getText();
		} else {
			return null;
		}
	}

	/**
	 * 取当前系统时间,格式:yyyyMMddHHmmss，例如20080808122135
	 * @return
	 */
	public static String getNow() {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		return sDateFormat.format(new Date());
	}

	public static int getRandomInt(int min,int max){
		int randomInt = min+(int)(Math.random() * max);
		return randomInt;
	}

	/**
	 * 取格式化时间,格式:yyyyMMddHHmmss，例如20080808122135
	 * @return
	 */
	public static String getFormatTimeString(Date date) {
		SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
		return sDateFormat.format(date);
	}

	/**
	 * 取格式化时间,格式:yyyyMMddHHmmss，例如20080808122135
	 * @return
	 */
	public static String getFormatTimeString(Date date,String datePattern) {
		if(date==null)
			return "";
		SimpleDateFormat sDateFormat = new SimpleDateFormat(datePattern);
		return sDateFormat.format(date);
	}

	/**
	 * 获取TimeStamp的字符串类型
	 * @return
	 */
	public static String getTimeString(Date date,String type) {
		String result="";
		if(type!=null&&type.toUpperCase().equals("LONG")&&date!=null){
			result =((Long)date.getTime()).toString();
		}
		return result;
	}

	/**
	 * 获取TimeStamp的字符串类型
	 * @return
	 */
	public static String getTimeStampString(Timestamp timestamp,String type) {
		String result="";
		if(type!=null&&type.toUpperCase().equals("LONG")&&timestamp!=null){
			result =((Long)timestamp.getTime()).toString();
		}
		return result;
	}

	/**
	 * 从字节数组到十六进制字符串转换
	 * @param b
	 * @return
	 */
	public static String byte2str(byte[] b) {
		byte[] buff = new byte[2 * b.length];
		for (int i = 0; i < b.length; i++) {
			buff[2 * i] = hex[(b[i] >> 4) & 0x0f];
			buff[2 * i + 1] = hex[b[i] & 0x0f];
		}
		return new String(buff);
	}

	/**
	 * 从十六进制字符串到字节数组转换
	 * @param hexstr
	 * @return
	 */
	public static byte[] str2byte(String hexstr) {
		byte[] b = new byte[hexstr.length() / 2];
		int j = 0;
		for (int i = 0; i < b.length; i++) {
			char c0 = hexstr.charAt(j++);
			char c1 = hexstr.charAt(j++);
			b[i] = (byte) ((parseInt(c0) << 4) | parseInt(c1));
		}
		return b;
	}

	/**
	 * 将字符转换成整数
	 * @param c
	 * @return
	 */
	private static int parseInt(char c) {
		return Integer.parseInt(String.valueOf(c), 16);
	}

	/**
	 *
	 * 函数名称：isBlank<br>
	 * 函数功能：检查字符串str去掉首尾空格是否为空值(null也为空值)<br>
	 * 例： StringUtil.isBlank("   abc ") 输出：false<br>
	 * @param str - 要检查的字符串<br>
	 * @return boolean str为空返回true，否则返回false
	 */
	public static boolean isBlank(String str) {
		return str == null || "".equals(str.trim());
	}

	/**
	 *
	 * 函数名称：decodeHTML<br>
	 * 函数功能：解码HTML(将&gt;,&lt;,&quot;,&amp;转换成>,<,",& )<br>
	 *  例：String temp="&lt;input type=text name='test' value='123' /&gt;"; <br>
	 *    System.out.println( StringUtil.decodeHTML(temp));<br>
	 *    输出：<input type=text name='test' value='123' />
	 * @param s - 解码字符串
	 * @return String
	 */
	public static String decodeHTML(String s) {
		if (isBlank(s))
			return "";
		s = s.replaceAll("&amp;", "&");
		s = s.replaceAll("&lt;", "<");
		s = s.replaceAll("&gt;", ">");
		s = s.replaceAll("&quot;", "\"");
		return s;
	}


	/**
	 *
	 * 函数名称：getIpAddr<br>
	 * 函数功能：获取客户端IP
	 * @param request
	 * @return String 客户端IP
	 */
	public static String getIpAddr(HttpServletRequest request) {
		String ip = request.getHeader("X-Forwarded-For");
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}

}
